/**
 * Notes: 设备订单控制器 - 宠物门店预约小程序
 * Date: 2025-01-27
 */

const BaseController = require('./base_controller.js');
const DeviceOrderService = require('../service/device_order_service.js');
const PaymentService = require('../service/payment_service.js');
const UserModel = require('../model/user_model.js');
const PassportService = require('../service/passport_service.js');

class DeviceOrderController extends BaseController {

	/**
	 * 创建设备使用订单
	 */
	async createDeviceOrder() {
		// 数据校验
		let rules = {
			deviceId: 'must|string|max:50|name=设备ID',
			duration: 'must|int|min:1|max:480|name=使用时长', // 最长8小时
			orderType: 'string|in:normal,extend|default:normal|name=订单类型',
			parentOrderId: 'string|max:50|name=原订单ID'
		};

		let input = this.validateData(rules);

		// 组合方案 2：下单前用户存在性校验与必要时自动建档
		let user = await UserModel.getOne({ _id: this._userId });
		if (!user) {
			const passport = new PassportService();
			await passport.registerUser(this._userId, {});
		}

		let service = new DeviceOrderService();
		return await service.createDeviceOrder(
			this._userId,
			input.deviceId,
			input.duration,
			input.orderType,
			input.parentOrderId
		);
	}

	/**
	 * 支付设备订单（余额支付）
	 */
	async payDeviceOrderWithBalance() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID'
		};

		let input = this.validateData(rules);

		let service = new DeviceOrderService();
		return await service.payDeviceOrder(input.orderId, 'balance');
	}

	/**
	 * 创建设备订单支付参数（微信支付）
	 */
	async createDeviceOrderPayment() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID'
		};

		let input = this.validateData(rules);

		// 获取订单信息
		const DeviceOrderModel = require('../model/device_order_model.js');
		const order = await DeviceOrderModel.getOne({ _id: input.orderId });
		if (!order) {
			throw new Error('订单不存在');
		}

		// 检查订单权限
		if (order.userId !== this._userId) {
			throw new Error('无权限访问此订单');
		}

		// 检查订单状态
		if (!DeviceOrderModel.canPay(order)) {
			throw new Error('订单状态不允许支付');
		}

		// 生成支付参数
		const paymentService = new PaymentService();
		const paymentParams = await paymentService.generateDeviceOrderPaymentParams(order);

		return {
			orderId: order._id,
			orderNumber: order.orderNumber,
			totalAmount: order.totalAmount,
			paymentParams: paymentParams
		};
	}

	/**
	 * 处理设备订单支付回调
	 */
	async handleDeviceOrderPaymentCallback() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID',
			transactionId: 'string|max:100|name=交易ID',
			payTime: 'int|name=支付时间',
			status: 'must|string|in:success,failed|name=支付状态'
		};

		let input = this.validateData(rules);

		let service = new DeviceOrderService();
		return await service.payDeviceOrder(input.orderId, 'wechat_pay', {
			transactionId: input.transactionId,
			payTime: input.payTime,
			status: input.status
		});
	}

	/**
	 * 获取用户设备订单列表
	 */
	async getUserDeviceOrders() {
		// 数据校验
		let rules = {
			page: 'int|min:1|default:1|name=页码',
			size: 'int|min:1|max:50|default:20|name=每页数量'
		};

		let input = this.validateData(rules);

		let service = new DeviceOrderService();
		return await service.getUserDeviceOrders(this._userId, input.page, input.size);
	}

	/**
	 * 获取设备订单详情
	 */
	async getDeviceOrderDetail() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID'
		};

		let input = this.validateData(rules);

		const DeviceOrderModel = require('../model/device_order_model.js');
		const deviceOrderModel = new DeviceOrderModel();
		const order = await deviceOrderModel.getOrderDetail(input.orderId, this._userId);
		
		if (!order) {
			throw new Error('订单不存在或无权限访问');
		}

		// 补充设备信息
		const DeviceModel = require('../model/device_model.js');
		const device = await DeviceModel.getOne({ _id: order.deviceId });
		if (device) {
			order.deviceInfo = {
				name: device.name,
				type: device.type,
				location: device.location
			};
		}

		// 补充门店信息
		const StoreModel = require('../model/store_model.js');
		const store = await StoreModel.getOne({ _id: order.storeId });
		if (store) {
			order.storeInfo = {
				name: store.name,
				address: store.address
			};
		}

		// 添加状态描述
		order.statusDesc = DeviceOrderModel.getStatusDesc(order.status);

		return order;
	}

	/**
	 * 取消设备订单
	 */
	async cancelDeviceOrder() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID'
		};

		let input = this.validateData(rules);

		const DeviceOrderModel = require('../model/device_order_model.js');
		const deviceOrderModel = new DeviceOrderModel();
		const order = await deviceOrderModel.getOrderDetail(input.orderId, this._userId);
		
		if (!order) {
			throw new Error('订单不存在或无权限访问');
		}

		// 检查订单状态
		if (order.status !== DeviceOrderModel.STATUS.PENDING_PAY) {
			throw new Error('只能取消待支付的订单');
		}

		// 更新订单状态为已取消
		await deviceOrderModel.updateStatus(input.orderId, DeviceOrderModel.STATUS.CANCELLED);

		return {
			success: true,
			message: '订单已取消',
			orderId: input.orderId
		};
	}

	/**
	 * 完成设备订单（管理员接口）
	 */
	async completeDeviceOrder() {
		// 数据校验
		let rules = {
			orderId: 'must|string|max:50|name=订单ID'
		};

		let input = this.validateData(rules);

		let service = new DeviceOrderService();
		return await service.completeDeviceOrder(input.orderId);
	}

	/**
	 * 检查并处理过期订单（定时任务接口）
	 */
	async checkExpiredOrders() {
		let service = new DeviceOrderService();
		return await service.checkExpiredOrders();
	}
}

module.exports = DeviceOrderController;